package com.jzr.common.util;

import java.lang.reflect.Array;

public class ArrayUtil {
    public static <T> T[] mergeArrays(T[]... arrays) {
        int lengthOfNewArray = 0;
        for (int i = 0; i < arrays.length; ++i) {
            lengthOfNewArray += arrays[i].length;
        }
        //使用(T[])Array.newInstance(...)可避免(T[])new Object[...]引发的ClassCastException
        T[] newArray = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), lengthOfNewArray);
        int destPos = 0;
        for (int i = 0; i < arrays.length; ++i) {
            System.arraycopy(arrays[i], 0, newArray, destPos, arrays[i].length);
            destPos += arrays[i].length;
        }
        return newArray;
    }

    public static int[] mergeArrays(int[]... arrays) {
        int lengthOfNewArray = 0;
        for (int i = 0; i < arrays.length; ++i) {
            lengthOfNewArray += arrays[i].length;
        }
        int[] newArray = new int[lengthOfNewArray];
        int destPos = 0;
        for (int i = 0; i < arrays.length; ++i) {
            System.arraycopy(arrays[i], 0, newArray, destPos, arrays[i].length);
            destPos += arrays[i].length;
        }
        return newArray;
    }
}
